from django.core.mail import send_mail
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from books.models import Book
# Create your views here.
def database_one(request):
	values = request.META.items()
	values.sort()
	html = []
	for k,v in values:
		html.append('<tr><td>%s</td><td>%s</td></tr>' % (k,v))
	return HttpResponse('<table>%s</table>' % '\n'.join(html))

def search_form(request):
	return render_to_response('serach_from.html')

def search(request):
	errors = []
	if 'q' in request.GET:
		q = request.GET['q']
		if not q:
			errors.append('Enter a search term')
		elif len(q) > 20:
			errors.append('Please submit a search term 20 characters or shorter.')
		else:		

			books = Book.objects.filter(title__icontains=q)
			return render_to_response('search_results.html',
				{'books': books,'query':q}
			)
	return render_to_response('search_form.html',{'errors': errors})

def contact(request):
	errors = []
	if request.method == 'POST':
		if not request.POST.get('subject',''):
			errors.append('Enter a subject.')
		if not request.POST.get('email',''):
			errors.append('Enter a message.')
		if request.POST.get('email') and '@' not in request.POST['email']:
			errors.append('Enter a valid e-mail address.')
		if not errors:
			send_mail(
				request.POST['subject'],
				request.POST['email'],
				request.POST.get('email','noreply@example.com'),
				['siteowner@example.com'],
			)
			return HttpResponseRedirect('/contact/thanks/')

	return render_to_response('contact_form.html',{'errors':errors})

def thinks(request):
	return HttpResponse('helloword')


def foo_view(request):
	return render_to_response('index.html')

def bar_view(request,template_name='jicheng_model.html'):
	var = 'aaa'
	return render_to_response(template_name,{'var':var})


def foobar_view(request,template_name):
	return render_to_response(template_name)

def my_view(request,month,day):
	ss = ' %s ......%s .......' % (month,day)
	return HttpResponse(ss)